//
//  HRCommentInfoViewController.m
//  Hear
//
//  Created by mac on 2017/10/11.
//  Copyright © 2017年 mac. All rights reserved.
// 评论详情

#import "HRCommentInfoViewController.h"
#import "HRCommentInfoHeadView.h"
#import "HRDynamicCommentTableViewCell.h"
#import "EMVoiceConverter.h"
#import "OSSImageUploader.h"
#import "HRDynamicInfoViewModel.h"
#import "HRDynamicViewController.h"
@interface HRCommentInfoViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)HRCommentInfoHeadView *headView;
@property (nonatomic, strong)UITableView *tableView;

@property (strong, nonatomic) HRMessageToolBar *chatToolbar;
@property(strong, nonatomic) EaseFaceView *faceView;
@property(strong, nonatomic) HRMeeageRecordView *recordView;
@property (weak, nonatomic) id<EaseMessageViewControllerDataSource> dataSource;
@property (weak, nonatomic) id<EaseMessageViewControllerDelegate> delegate;
@property (nonatomic, strong)HRDynamicCommentModel *tempCommentModel; // 回复的人的model

@property(nonatomic, strong)HRDynamicCommentModel *lastCommentModel;

@property(nonatomic, strong)HRDynamicInfoViewModel *viewModel;

@property(nonatomic, strong)HRDynamicCommentTableViewCell *tempCell;

@end

@implementation HRCommentInfoViewController
#pragma mark - Get and Set

-(HRDynamicInfoViewModel *)viewModel{
    if (!_viewModel){
        _viewModel = [HRDynamicInfoViewModel new];
    }
    return _viewModel;
}

- (HRCommentInfoHeadView *)headView{
    if (_headView == nil) {
        _headView = [[HRCommentInfoHeadView alloc] init];
        _headView.frame = CGRectMake(0, 0, kFullWidth, 0);
        _headView.commentModel = self.commentModel;
        _headView.height = _headView.headHeight;
    }
    return _headView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
//    UIButton *leftButton = [UIButton buttonWithType:0];
//    leftButton.size = CGSizeMake(20, 20);
//    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:UIControlStateNormal];
//    [leftButton addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//    self.navigationItem.leftBarButtonItem = leftItem;
    

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = self.headView;
    
    
    CGFloat chatbarHeight = [HRMessageToolBar defaultHeight];
    self.chatToolbar = [[HRMessageToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - chatbarHeight, self.view.frame.size.width, chatbarHeight) keyboardType:DXKeyboardTypeNoPhoto];
    self.chatToolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    self.chatToolbar.inputTextView.placeHolder = [NSString stringWithFormat:@"发言"];
    
    [self setupEmotion];

    self.tempCommentModel = self.commentModel;
    
}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.commentModel.ChildComments.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HRDynamicCommentTableViewCell *cell = [HRDynamicCommentTableViewCell cellWithTableView:tableView];
    HRDynamicCommentModel *model = self.commentModel.ChildComments[indexPath.row];
    if (model){
        cell.commentModel = model;
    }
    WeakSelf
    cell.iconTapBock = ^(NSString *currentUserID){
        HRDynamicViewController *VC = [HRDynamicViewController new];
        VC.currentUserID = model.UserLocalId;
        [weakSelf.navigationController pushViewController:VC animated:YES];
    };
    cell.playCommentMedioBlock = ^(HRDynamicCommentModel *currentCommentModel){
        if (currentCommentModel || weakSelf.lastCommentModel){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if(![currentCommentModel.LocalId isEqualToString:weakSelf.lastCommentModel.LocalId]){
                    weakSelf.lastCommentModel.isPlaying = NO;
                    [weakSelf.tempCell.soundButton.voiceImageView stopAnimating];
                }
                if (model.isPlaying){
                    [cell.soundButton.voiceImageView startAnimating];
                }else{
                    [cell.soundButton.voiceImageView stopAnimating];
                }
                weakSelf.lastCommentModel = currentCommentModel;
                weakSelf.tempCell = cell;
            });
            
        }
        
        
    };
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    HRDynamicCommentModel *model = self.commentModel.ChildComments[indexPath.row];
    return model.cellHeight;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self towAnswerForSomenone:self.commentModel.ChildComments[indexPath.row]];
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.commentModel.ChildComments.count) return NO;
    HRDynamicCommentModel *model = self.commentModel.ChildComments[indexPath.row];
    if (model){
        if ([model.UserLocalId isEqualToString:USERID]){
            return YES;
        }
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [self deleteCommentIndex:indexPath.row];
    }
    
}

#pragma 二级评论
- (void)towAnswerForSomenone:(HRDynamicCommentModel *)commentModel{
    
    if ([commentModel.UserLocalId isEqualToString:USERID]){
        self.chatToolbar.inputTextView.placeHolder = [NSString stringWithFormat:@"发言"];
        self.tempCommentModel = nil;
    }else{
        self.chatToolbar.inputTextView.placeHolder = [NSString stringWithFormat:@"回复：%@",commentModel.CommentUserNickName];
        self.tempCommentModel = commentModel;
    }
}

- (void)deleteCommentIndex:(NSUInteger)index{
    HRDynamicCommentModel *model = self.commentModel.ChildComments[index];
    
    WeakSelf
    if ([model.UserLocalId isEqualToString:USERID]){
        [self.viewModel deleteComment:@{@"LocalId":model.LocalId,@"UserLocalId":USERID} isSeccess:^(BOOL isSeccess) {
            if (isSeccess){
                [weakSelf.commentModel.ChildComments removeObjectAtIndex:index];
                [weakSelf.tableView reloadData];
                [MBProgressHUD showMessage:@"删除成功" finishBlock:nil];
            }
        }];
    }
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.chatToolbar endEditing:YES];

}

- (void)setChatToolbar:(HRMessageToolBar *)chatToolbar
{
    [_chatToolbar removeFromSuperview];
    
    _chatToolbar = chatToolbar;
    if (_chatToolbar) {
        [self.view addSubview:_chatToolbar];
    }
    
    CGRect tableFrame = self.tableView.frame;
    tableFrame.size.height = self.view.frame.size.height - _chatToolbar.frame.size.height;
    self.tableView.frame = tableFrame;
    if ([chatToolbar isKindOfClass:[HRMessageToolBar class]]) {
        [(HRMessageToolBar *)self.chatToolbar setDelegate:self];
        //        self.chatBarMoreView = (EaseChatBarMoreView*)[(HRMessageToolBar *)self.chatToolbar moreView];
        self.faceView = (EaseFaceView*)[(HRMessageToolBar *)self.chatToolbar faceView];
    }
}
- (void)setDataSource:(id<EaseMessageViewControllerDataSource>)dataSource
{
    //    _dataSource = dataSource;
    
    [self setupEmotion];
}

#pragma mark - EMChatToolbarDelegate

- (void)didChangeFrameToHeight:(CGFloat)toHeight
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = self.tableView.frame;
        rect.origin.y = 0;
        rect.size.height = self.view.frame.size.height - toHeight;
        self.tableView.frame = rect;
    }];
    
    [self _scrollViewToBottom:NO];
}
/*!
 @method
 @brief 设置表情
 @discussion 加载默认表情，如果子类实现了dataSource的自定义表情回调，同时会加载自定义表情
 @result
 */
- (void)setupEmotion
{
    if ([self.dataSource respondsToSelector:@selector(emotionFormessageViewController:)]) {
        NSArray* emotionManagers = [self.dataSource emotionFormessageViewController:self];
        [self.faceView setEmotionManagers:emotionManagers];
    } else {
        NSMutableArray *emotions = [NSMutableArray array];
        for (NSString *name in [EaseEmoji allEmoji]) {
            EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:name emotionThumbnail:name emotionOriginal:name emotionOriginalURL:@"" emotionType:EMEmotionDefault];
            [emotions addObject:emotion];
        }
        EaseEmotion *emotion = [emotions objectAtIndex:0];
        EaseEmotionManager *manager= [[EaseEmotionManager alloc] initWithType:EMEmotionDefault emotionRow:3 emotionCol:7 emotions:emotions tagImage:[UIImage imageNamed:emotion.emotionId]];
        [self.faceView setEmotionManagers:@[manager]];
    }
}

- (void)didStartRecordingVoiceAction:(UIView *)recordView
{
    if ([self _canRecord]) {
        
        int x = arc4random() % 100000;
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
        
        [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error)
         {
             if (error) {
                 NSLog(@"%@",NSEaseLocalizedString(@"message.startRecordFail", @"failure to start recording"));
             }
         }];
    }
}

- (void)didCancelRecordingVoiceAction:(UIView *)recordView
{
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
    
}

#pragma 发送语音
- (void)didFinishRecoingVoiceAction:(UIView *)recordView andRecordPath:(NSString *)recordPath andDuration:(NSInteger)aDuration
{
    
    NSString *wavFilePath = [[recordPath stringByDeletingPathExtension]
                             stringByAppendingPathExtension:@"wav"];
    BOOL convertResult = [self convertAMR:recordPath toWAV:wavFilePath];
    if (convertResult){
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:recordPath error:nil];
        
    }else{
        
    }
    
    [self answerComment:wavFilePath andType:@"2" andUrlLength:[NSString stringWithFormat:@"%d",aDuration]];
}

- (BOOL)convertAMR:(NSString *)amrFilePath
             toWAV:(NSString *)wavFilePath
{
    BOOL ret = NO;
    BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:amrFilePath];
    if (isFileExists) {
        [EMVoiceConverter amrToWav:amrFilePath wavSavePath:wavFilePath];
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:wavFilePath];
        if (isFileExists) {
            ret = YES;
        }
    }
    
    return ret;
}

- (void)didDragInsideAction:(UIView *)recordView
{
    if ([self.recordView isKindOfClass:[HRMeeageRecordView class]]) {
        [(HRMeeageRecordView *)self.recordView recordButtonDragInside];
    }
}

- (void)didDragOutsideAction:(UIView *)recordView
{
    if ([self.recordView isKindOfClass:[HRMeeageRecordView class]]) {
        [(HRMeeageRecordView *)self.recordView recordButtonDragOutside];
    }
}

/*!
 @method
 @brief tableView滑动到底部
 @discussion
 @result
 */
- (void)_scrollViewToBottom:(BOOL)animated
{
    if (self.tableView.contentSize.height > self.tableView.frame.size.height)
    {
        CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
        [self.tableView setContentOffset:offset animated:animated];
    }
}
/*!
 @method
 @brief 当前设备是否可以录音
 @discussion
 @result
 */
- (BOOL)_canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    
    return bCanRecord;
}

- (void)didSendText:(NSString *)text
{
    
    if (text && text.length > 0) {
        //        [self sendTextMessage:text];
        //        [self.atTargets removeAllObjects];
        [self answerComment:text andType:@"1" andUrlLength:@"0"];
        
    }
}

#pragma 评论
- (void)answerComment:(NSString *)contentStr andType:(NSString *)type andUrlLength:(NSString *)urlLength{
    WeakSelf
    if ([type isEqualToString:@"2"]){
        [OSSImageUploader asyncUploadSound:@[contentStr] complete:^(NSArray<NSString *> *names, UploadImageState state) {
            if (state == UploadImageFailed) return ;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf postAnswerComment:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]] andType:type andUrlLength:urlLength];
            });
        }];
    }else{
        [weakSelf postAnswerComment:contentStr andType:type andUrlLength:urlLength];
    }
}



- (void)postAnswerComment:(NSString *)contentStr andType:(NSString *)type andUrlLength:(NSString *)urlLength{
    WeakSelf
    
    HRDynamicCommentRequestModel *requestModel = [HRDynamicCommentRequestModel new];
    requestModel.LocalId = USERID;
    requestModel.UserLocalId = USERID;
    requestModel.MomentLocalId = self.dynamicLocalId;
    requestModel.CommentText = contentStr;
    
    requestModel.IsRead = 0;
    
    requestModel.ReplyUserLocalId = self.tempCommentModel.UserLocalId;
    requestModel.MainCommentLocalId = self.commentModel.LocalId;
    
    if ([self.chatToolbar.inputTextView.placeHolder isEqualToString:@"发言"]){
        requestModel.CommentLevel = @"2";
    }else{
        requestModel.CommentLevel = @"3";
    }
    
    requestModel.CreateTime = [weakSelf getCurrentTime];
    requestModel.CommentType = type;
    requestModel.SoundLength = urlLength;
    requestModel.SoundUrl = contentStr;
    if ([type isEqualToString:@"2"]){
        requestModel.CommentText = @"";
    }else{
        requestModel.SoundLength = @"0";
        requestModel.SoundUrl = @"";
    }
    
    
    [weakSelf.viewModel postDynamicCommentParam:requestModel AndCommentModel:^(HRDynamicCommentModel *commentModel) {
        
        weakSelf.tempCommentModel = nil;
        
        weakSelf.chatToolbar.inputTextView.placeHolder = [NSString stringWithFormat:@"发言"];
        
        if (commentModel){
            [weakSelf.commentModel.ChildComments insertObject:commentModel atIndex:0];
        }
//        weakSelf.layout.dynamicModel.CommentCount += 1;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
        });
        
        [weakSelf.chatToolbar endEditing:YES];
        
        
        
        [MBProgressHUD showMessage:@"评论成功" finishBlock:nil];
    }];
}

- (NSString *)getCurrentTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.hidesBottomBarWhenPushed = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.chatToolbar endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
